﻿using System.Globalization;
using KPIS.GERP.MVC.Classes;
using KPIS.GERP.MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KPIS.GERP.MVC.SysApprovalService;
using KPIS.GERP.Models;
using KPIS.GERP.Models.HRM;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.SERVICE.Model;

namespace KPIS.GERP.MVC.Controllers
{
    public class AbsenceController : Controller
    {
        public static string AbsenceId;
        private GERPContext db = new GERPContext(true);
        public SsMng ssMng = new SsMng();

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
         
        [HandleError]
        public ActionResult Index()
        {
            string EmpId = ssMng.EmpSeq;
            string bgm_year = (new ThaiBuddhistCalendar().GetYear(DateTime.Now)).ToString();
            List<KPIS.GERP.Models.HRM.PsAbsence> lst;
            try
            { 
                using (var db = new GERPContext(true))
                {
                    lst = db.PsAbsences.OrderByDescending(o=>o.AbsenceId).ToList();
                }
            }catch(Exception ex)
            {
                ex.Data.Add("Error message", "มีปัญหาในการเชื่อมต่อฐานข้อมูล"); 
                throw ex;
            }
            ViewBag.AbsenceTypes = AbsenceTypeDataSource(); 
            return View(lst);
        }

        public ActionResult CreateAbsence()
        {
            ViewBag.AbsenceTypes = AbsenceTypeDataSource();
            ViewBag.requestTitle = DefaultApprovalTitle();
            return View();
        }

        [HttpPost]
        public ActionResult CreateAbsence(PsAbsence item, int? AbsenceTypeId = null, string requestTitle = "", string requesterEmpSeq = null)
        {
            if (!item.StartDate.HasValue)
            {
                ViewBag.Message = "กรุณาเลือกวันเริ่มลา";
            }
            else if (!item.EndDate.HasValue)
            {
                ViewBag.Message = "กรุณาเลือกวันสิ้นสุดการลา";
            }
            else if (string.IsNullOrWhiteSpace(requesterEmpSeq))
            {
                ViewBag.Message = "กรุณาเลือกผู้ขอลา";
            }
            else
            {
                requestTitle = string.IsNullOrWhiteSpace(requestTitle) ? DefaultApprovalTitle() : requestTitle;
                item.EmpId = Convert.ToInt32(requesterEmpSeq);
                item.CreatedBy = ssMng.EmpSeqI;
                try
                {
                    using (var wf = new CheckRulesServiceIisRef.CheckRulesServiceClient())
                    {
                        var req = wf.GetRequestData(item.EmpId.ToString(), item.AbsenceTypeId.ToString(),
                                                    (DateTime) item.StartDate, (DateTime) item.EndDate, 
                                                    item.ContactAddress, item.Description,
                                                    item.CreatedBy.ToString(), item.StartTime, item.EndTime, 
                                                    requestTitle, out AbsenceId);

                        ViewBag.Message = req;
                        ViewBag.Sequence = AbsenceId;

                        if (!String.IsNullOrEmpty(AbsenceId))
                            item.AbsenceId = Convert.ToInt32(AbsenceId);
                    }
                    //int intEmpSeq = new SsMng().EmpSeqI;
                    //using(var service = new SysApprovalServiceClient())
                    //{
                    //    var result = service.CreateApprovalTask(new KPIS.GERP.Models.SYS.ViewModel.CreateApprovalTaskVM
                    //        {
                    //            RequestTitle = "[คำสั่งบรรจุ]" + model.CmdName,
                    //            ApplyToEmpId = intEmpSeq,
                    //            RefId = model.CmdId,
                    //            ApproveProcessEnum = ApproveProcessEnum.คำสั่ง,
                    //            ConfirmAs = "P",
                    //            ApproveAs = "A",
                    //            CreateByEmpId = intEmpSeq
                    //        });
                    //}

                }
                catch (HttpException ex)
                {
                    ex.Data.Add("Error message", "อินเตอร์เน็ตไม่สามารถใช้งานได้");
                    throw ex;
                }
                catch (Exception ex)
                {
                    ex.Data.Add("Error message", "ไม่สามารถใช้งานได้เนื่องจาก:" + ex.Message);
                    throw ex;
                }
            }

            ViewBag.AbsenceTypes = AbsenceTypeDataSource(AbsenceTypeId);

            ViewBag.requestTitle = requestTitle;

            if (item.AbsenceId != 0)
                return RedirectToAction("ViewDetails", new { RefSeq = item.AbsenceId });

            return View(item);
        }

        public ActionResult Confirm(int? EmpId, int AbsenceId, string status, string requestTitle, int? AbsenceTypeId = null)
        {
            //requestTitle = string.IsNullOrWhiteSpace(requestTitle) ? DefaultApprovalTitle() : requestTitle;
            if(status == "D")
            {
                var absence = db.PsAbsences.Find(AbsenceId);
                absence.RecordStatus = "D";
                absence.UpdatedBy = ssMng.EmpSeqI;
                absence.UpdatedWhen = DateTime.Now; //new PsAbsence().UpdateStatusHrmPsAbsence(AbsenceId.ToString(), "D", ssMng.EmpSeq));
                return RedirectToAction("Index", "Absence");
            }
            else if (String.IsNullOrWhiteSpace(EmpId.ToString()) || 
                String.IsNullOrWhiteSpace(AbsenceId.ToString()) || 
                String.IsNullOrWhiteSpace(status) ||
                String.IsNullOrWhiteSpace(requestTitle))
            {
                ViewBag.Message = "รูปแบบข้อมูลไม่ถูกต้อง";
                return RedirectToAction("CreateAbsence", "Absence");
            }
            else
            {
                PsAbsence absence = null;
                SendApproval app = new SendApproval();
                app.Title = requestTitle;
                app.AbsenceSeq = AbsenceId;
                app.EmpSeq = EmpId.Value;

                app.Status = status;
                if(AbsenceTypeId == null)
                    using (var db = new GERPContext(true))
                    {
                        absence = db.PsAbsences.Find(AbsenceId);
                        if (absence == null || absence.AbsenceTypeId == null)
                        {
                            throw new Exception("หาข้อมูลคำขอลาไม่พบ");
                        } 
                        AbsenceTypeId = absence.AbsenceTypeId;
                    } 

                try
                {
                    int createdBy = absence != null && absence.CreatedBy.HasValue ? absence.CreatedBy.Value : ssMng.EmpSeqI;
                    int requestBy = absence.EmpId.Value;

                    //using (var serviceClient = new ApprovalServiceIisRef.ServiceClient())
                    //{
                    //    string outMessage;
                    //    serviceClient.CreateAbsenceTask(app.Title, requestBy, app.AbsenceSeq, app.Status, AbsenceTypeId.Value, "A", createdBy, out outMessage);
                    //    ViewBag.Message = outMessage;
                    //} 
                    using(var service = new SysApprovalServiceClient())
                    {
                        var result = service.CreateApprovalTask(new KPIS.GERP.Models.SYS.ViewModel.CreateApprovalTaskVM
                            {
                                RequestTitle = app.Title,
                                ApplyToEmpId = requestBy,
                                RefId = app.AbsenceSeq,
                                ApproveProcessEnum = (ApproveProcessEnum) AbsenceTypeId.Value,
                                ConfirmAs = app.Status,
                                ApproveAs = "A",
                                CreateByEmpId = createdBy
                            });
                    }
                }
                catch (HttpException ex)
                {
                    ex.Data.Add("Error message", "อินเตอร์เน็ตไม่สามารถใช้งานได้:" + ex.Message);
                    throw ex;
                }
                catch (Exception ex)
                {
                    ex.Data.Add("Error message", "ไม่สามารถใช้งานได้เนื่องจาก:" + ex.Message);
                    throw ex;
                }
                return RedirectToAction("ViewDetails", "Absence", new { RefSeq = AbsenceId });
            }
        }

        public ActionResult ViewDetails(int RefSeq)
        {
            ApprovalTask approvalTaskModel;
            PsAbsence hrmPsAbsence;
            using (var db = new GERPContext(true))
            {
                hrmPsAbsence = db.PsAbsences.Find(RefSeq);
                ViewBag.AbsenceModel = hrmPsAbsence;
                approvalTaskModel = db.ApprovalTasks.FirstOrDefault(o=>o.RefId == RefSeq && o.OriginalAppPrcId == hrmPsAbsence.AbsenceTypeId.Value);// new ApprovalTaskDal().GetApprovalTask(new approval_task {Reference = new approval_reference {ref_seq = RefSeq, rule_approve_type_seq = hrmPsAbsence.AbsenceTypeId.Value}}).FirstOrDefault();
            }
            ApprovalTask model = approvalTaskModel;
            //using (var serviceClient = new ApprovalServiceWcfIisRef.AbsenceApprovalWCFClient())
            //{
            //    var data = serviceClient.GetTasks();
            //    model = (from a in data
            //             where a.Reference.ref_seq == RefSeq && a.Reference.rule_approve_group_seq == 1
            //             select a).FirstOrDefault();
            //    if(model == null)
            //        using (var serviceClientWf = new ApprovalServiceIisRef.ServiceClient())
            //        {
            //            try
            //            {
            //                model = serviceClientWf.GetApprovalTask(approvalTaskModel.WfInstantId);
            //            } catch (Exception ex)
            //            {

            //            }
            //        }
            //}
            return View(model);
        }

        public IEnumerable<SelectListItem> AbsenceTypeDataSource(int? absenceTypeSeq = null)
        {
            return db.PsAbsenceTypes.Select(c => new SelectListItem
                {
                    Value = c.AbsenceTypeId.ToString(),
                    Text = c.AbsenceTypeName,
                    Selected = absenceTypeSeq.HasValue && c.AbsenceTypeId == absenceTypeSeq
                });
            //return new AbsenceTypes().GetAllAbsenceTypes()
            //    .Select(c => new SelectListItem
            //    {
            //        Value = c.AbsenceTypeId.ToString(),
            //        Text = c.absence_type_name.ToString(),
            //        Selected = absenceTypeSeq.HasValue && c.AbsenceTypeId == absenceTypeSeq
            //    });
        }

        public string DefaultApprovalTitle()
        {
            return "คำขอลาของ" + ssMng.UserName;
        }
    }
}
